<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="专家姓名">
          <el-input v-model="queryParams.name" placeholder="请输入专家姓名" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="专业类型">
          <el-select v-model="queryParams.professionType" placeholder="请选择专业类型" clearable style="width: 200px;">
            <el-option v-for="item in professionTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="擅长领域">
          <el-input v-model="queryParams.specialty" placeholder="请输入擅长领域" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="button-area">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleEdit" :disabled="selectionList.length !== 1">编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete" :disabled="selectionList.length === 0">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格展示区域 -->
    <el-table
      v-loading="loading"
      :data="expertList"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="name" label="专家姓名" min-width="120"></el-table-column>
      <el-table-column prop="professionType" label="专业类型" min-width="120">
        <template slot-scope="scope">
          {{ getProfessionTypeName(scope.row.professionType) }}
        </template>
      </el-table-column>
      <el-table-column prop="position" label="职称" min-width="100"></el-table-column>
      <el-table-column prop="workUnit" label="工作单位" min-width="150"></el-table-column>
      <el-table-column prop="address" label="地址" min-width="150"></el-table-column>
      <el-table-column prop="contact" label="联系方式" min-width="120"></el-table-column>
      <el-table-column prop="specialty" label="擅长领域" min-width="150"></el-table-column>
      <el-table-column label="操作" min-width="180" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">详情</el-button>
          <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-area">
      <el-pagination
        v-show="total > 0"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑专家信息' : '添加专家信息'"
      :visible.sync="dialogVisible"
      width="800px"
      @close="handleClose"
    >
      <el-form ref="expertForm" :model="expertForm" :rules="expertRules" label-width="100px" class="expert-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="专家姓名" prop="name">
              <el-input v-model="expertForm.name" placeholder="请输入专家姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="expertForm.gender" placeholder="请选择性别">
                <el-option label="男" value="male"></el-option>
                <el-option label="女" value="female"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-input v-model="expertForm.nation" placeholder="请输入民族"></el-input>
            </el-form-item>
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-input v-model="expertForm.politicalStatus" placeholder="请输入政治面貌"></el-input>
            </el-form-item>
            <el-form-item label="办公电话" prop="officePhone">
              <el-input v-model="expertForm.officePhone" placeholder="请输入办公电话"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="expertForm.contact" placeholder="请输入联系方式"></el-input>
            </el-form-item>
            <el-form-item label="传真" prop="fax">
              <el-input v-model="expertForm.fax" placeholder="请输入传真"></el-input>
            </el-form-item>
            <el-form-item label="E-Mail" prop="email">
              <el-input v-model="expertForm.email" placeholder="请输入E-Mail" type="email"></el-input>
            </el-form-item>
            <el-form-item label="最高学历" prop="education">
              <el-input v-model="expertForm.education" placeholder="请输入最高学历"></el-input>
            </el-form-item>
            <el-form-item label="所学专业" prop="major">
              <el-input v-model="expertForm.major" placeholder="请输入所学专业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker v-model="expertForm.birthDate" type="date" placeholder="请选择出生日期" style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="职称" prop="position">
              <el-select v-model="expertForm.position" placeholder="请选择职称">
                <el-option label="高级工程师" value="senior_engineer"></el-option>
                <el-option label="工程师" value="engineer"></el-option>
                <el-option label="教授" value="professor"></el-option>
                <el-option label="研究员" value="researcher"></el-option>
                <el-option label="副研究员" value="associate_researcher"></el-option>
                <el-option label="助理工程师" value="assistant_engineer"></el-option>
                <el-option label="副教授" value="associate_professor"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="专业类型" prop="professionType">
              <el-select v-model="expertForm.professionType" placeholder="请选择专业类型">
                <el-option v-for="item in professionTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属类型" prop="affiliationType">
              <el-select v-model="expertForm.affiliationType" placeholder="请选择所属类型">
                <el-option label="政府所属" value="government"></el-option>
                <el-option label="企业所属" value="enterprise"></el-option>
                <el-option label="高校所属" value="university"></el-option>
                <el-option label="科研机构所属" value="research_institute"></el-option>
                <el-option label="部门所属" value="department"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工作单位" prop="workUnit">
              <el-input v-model="expertForm.workUnit" placeholder="请输入工作单位"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="expertForm.address" placeholder="请输入地址"></el-input>
            </el-form-item>
            <el-form-item label="职别" prop="jobTitle">
              <el-select v-model="expertForm.jobTitle" placeholder="请选择职别">
                <el-option label="自然灾害专家" value="natural_disaster"></el-option>
                <el-option label="事故灾难专家" value="accident_disaster"></el-option>
                <el-option label="公共卫生专家" value="public_health"></el-option>
                <el-option label="社会安全专家" value="social_security"></el-option>
                <el-option label="综合专家" value="comprehensive"></el-option>
                <el-option label="消防救援专家" value="fire_rescue"></el-option>
                <el-option label="生态环境专家" value="ecological_environment"></el-option>
                <el-option label="其他专家" value="other"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-form-item label="擅长领域" prop="specialty">
          <el-input v-model="expertForm.specialty" type="textarea" rows="3" placeholder="请输入擅长领域"></el-input>
        </el-form-item>
        <el-form-item label="工作简历" prop="workExperience">
          <el-input v-model="expertForm.workExperience" type="textarea" rows="3" placeholder="请输入工作简历"></el-input>
        </el-form-item>
        <el-form-item label="专家照片">
          <div class="upload-image">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="expertForm.photoUrl" :src="expertForm.photoUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="upload-hint">请上传大小不超过10MB格式为png/jpg/jpeg的文件</div>
          </div>
        </el-form-item>
        <el-form-item label="工作简历">
          <el-upload
            class="upload-file"
            :action="uploadUrl"
            :on-success="handleResumeSuccess"
            :before-upload="beforeFileUpload"
            :file-list="resumeFileList"
            :limit="1"
            :auto-upload="true"
          >
            <el-button size="small" type="primary">选取文件</el-button>
          </el-upload>
          <div class="upload-hint">请上传大小不超过10MB格式为doc/pdf的文件</div>
        </el-form-item>
        <el-form-item label="推荐表">
          <el-upload
            class="upload-file"
            :action="uploadUrl"
            :on-success="handleRecommendationSuccess"
            :before-upload="beforeFileUpload"
            :file-list="recommendationFileList"
            :limit="1"
            :auto-upload="true"
          >
            <el-button size="small" type="primary">选取文件</el-button>
          </el-upload>
          <div class="upload-hint">请上传大小不超过10MB格式为doc/pdf的文件</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="expertForm.remark" type="textarea" rows="2" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="专家详情"
      :visible.sync="detailDialogVisible"
      width="700px"
      @close="handleDetailClose"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="专家姓名">{{ detailForm.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ detailForm.gender === 'male' ? '男' : '女' }}</el-descriptions-item>
        <el-descriptions-item label="民族">{{ detailForm.nation }}</el-descriptions-item>
        <el-descriptions-item label="政治面貌">{{ detailForm.politicalStatus }}</el-descriptions-item>
        <el-descriptions-item label="办公电话">{{ detailForm.officePhone }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ detailForm.contact }}</el-descriptions-item>
        <el-descriptions-item label="E-Mail">{{ detailForm.email }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatDate(detailForm.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="职称">{{ getPositionName(detailForm.position) }}</el-descriptions-item>
        <el-descriptions-item label="专业类型">{{ getProfessionTypeName(detailForm.professionType) }}</el-descriptions-item>
        <el-descriptions-item label="工作单位">{{ detailForm.workUnit }}</el-descriptions-item>
        <el-descriptions-item label="擅长领域">{{ detailForm.specialty }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDetailClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from '@/utils/auth'

export default {
  name: 'ExpertManagement',
  data() {
    return {
      // 加载状态
      loading: false,
      // 分页信息
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        professionType: '',
        specialty: ''
      },
      // 专家列表数据
      expertList: [],
      // 选中项
      selectionList: [],
      // 弹窗可见性
      dialogVisible: false,
      detailDialogVisible: false,
      // 是否编辑模式
      isEdit: false,
      // 表单数据
      expertForm: {
        id: '',
        name: '',
        gender: '',
        nation: '',
        politicalStatus: '',
        officePhone: '',
        contact: '',
        fax: '',
        email: '',
        education: '',
        major: '',
        birthDate: '',
        position: '',
        professionType: '',
        affiliationType: '',
        workUnit: '',
        address: '',
        jobTitle: '',
        specialty: '',
        workExperience: '',
        photoUrl: '',
        resumeFileUrl: '',
        recommendationFileUrl: '',
        remark: ''
      },
      // 详情表单
      detailForm: {},
      // 文件列表
      resumeFileList: [],
      recommendationFileList: [],
      // 文件上传路径
      uploadUrl: '/api/common/upload',
      // 专业类型选项
      professionTypeOptions: [
        { label: '自然灾害专家', value: 'natural_disaster' },
        { label: '事故灾难专家', value: 'accident_disaster' },
        { label: '公共卫生专家', value: 'public_health' },
        { label: '社会安全专家', value: 'social_security' },
        { label: '生态环境专家', value: 'ecological_environment' }
      ],
      // 表单验证规则
      expertRules: {
        name: [{ required: true, message: '请输入专家姓名', trigger: 'blur' }],
        contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取专家列表
    getList() {
      this.loading = true
      // 模拟数据，实际应调用API
      setTimeout(() => {
        this.expertList = [
          {
            id: '1',
            name: '王宾',
            gender: 'male',
            nation: '汉',
            politicalStatus: '党员',
            officePhone: '010-12345678',
            contact: '13800138001',
            email: 'wangbin@example.com',
            birthDate: '1970-01-01',
            position: '研究员',
            professionType: 'ecological_environment',
            workUnit: '环保研究院',
            address: '北京市海淀区',
            specialty: '环境监察'
          },
          {
            id: '2',
            name: '陆战志',
            gender: 'male',
            nation: '汉',
            politicalStatus: '群众',
            officePhone: '010-87654321',
            contact: '13900139001',
            email: 'luzh@example.com',
            birthDate: '1975-05-10',
            position: '工程师',
            professionType: 'ecological_environment',
            workUnit: '环保公司',
            address: '上海市浦东新区',
            specialty: '环境监察'
          },
          {
            id: '3',
            name: '李国强',
            gender: 'male',
            nation: '汉',
            politicalStatus: '党员',
            officePhone: '020-12345678',
            contact: '13700137001',
            email: 'ligq@example.com',
            birthDate: '1968-11-15',
            position: '工程师',
            professionType: 'ecological_environment',
            workUnit: '环保部门',
            address: '广州市天河区',
            specialty: '环境监察'
          }
        ]
        this.total = this.expertList.length
        this.loading = false
      }, 500)
    },
    
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: '',
        professionType: '',
        specialty: ''
      }
      this.getList()
    },
    
    // 分页处理
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    
    // 选择变更
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    
    // 新增专家
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },
    
    // 编辑专家
    handleEdit(row) {
      this.isEdit = true
      this.resetForm()
      // 如果传入的是row，则编辑单条
      if (row) {
        this.expertForm = { ...row }
      } else if (this.selectionList.length === 1) {
        this.expertForm = { ...this.selectionList[0] }
      }
      this.dialogVisible = true
    },
    
    // 查看详情
    handleView(row) {
      this.detailForm = { ...row }
      this.detailDialogVisible = true
    },
    
    // 删除专家
    handleDelete(row) {
      const ids = row ? [row.id] : this.selectionList.map(item => item.id)
      this.$confirm('确定要删除选中的专家信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        setTimeout(() => {
          this.$message.success('删除成功')
          this.getList()
        }, 300)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 导出
    handleExport() {
      this.$message.success('导出成功')
    },
    
    // 表单重置
    resetForm() {
      this.expertForm = {
        id: '',
        name: '',
        gender: '',
        nation: '',
        politicalStatus: '',
        officePhone: '',
        contact: '',
        fax: '',
        email: '',
        education: '',
        major: '',
        birthDate: '',
        position: '',
        professionType: '',
        affiliationType: '',
        workUnit: '',
        address: '',
        jobTitle: '',
        specialty: '',
        workExperience: '',
        photoUrl: '',
        resumeFileUrl: '',
        recommendationFileUrl: '',
        remark: ''
      }
      this.resumeFileList = []
      this.recommendationFileList = []
      if (this.$refs.expertForm) {
        this.$refs.expertForm.resetFields()
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.expertForm.validate((valid) => {
        if (valid) {
          // 模拟提交
          setTimeout(() => {
            this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
            this.dialogVisible = false
            this.getList()
          }, 500)
        }
      })
    },
    
    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false
      this.resetForm()
    },
    
    // 关闭详情弹窗
    handleDetailClose() {
      this.detailDialogVisible = false
    },
    
    // 处理照片上传成功
    handleAvatarSuccess(res, file) {
      this.expertForm.photoUrl = URL.createObjectURL(file.raw)
    },
    
    // 处理简历上传成功
    handleResumeSuccess(res, file) {
      this.expertForm.resumeFileUrl = URL.createObjectURL(file.raw)
      this.resumeFileList = [file]
    },
    
    // 处理推荐表上传成功
    handleRecommendationSuccess(res, file) {
      this.expertForm.recommendationFileUrl = URL.createObjectURL(file.raw)
      this.recommendationFileList = [file]
    },
    
    // 照片上传前验证
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJPG) {
        this.$message.error('只支持jpg/png/jpeg格式！')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过10MB！')
      }
      return isJPG && isLt10M
    },
    
    // 文件上传前验证
    beforeFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      const isDoc = file.type === 'application/msword' || file.type === 'application/pdf' || file.name.endsWith('.docx')
      if (!isDoc) {
        this.$message.error('只支持doc/docx/pdf格式！')
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10MB！')
      }
      return isDoc && isLt10M
    },
    
    // 获取职称名称
    getPositionName(value) {
      const positionMap = {
        'senior_engineer': '高级工程师',
        'engineer': '工程师',
        'professor': '教授',
        'researcher': '研究员',
        'associate_researcher': '副研究员',
        'assistant_engineer': '助理工程师',
        'associate_professor': '副教授'
      }
      return positionMap[value] || value
    },
    
    // 获取专业类型名称
    getProfessionTypeName(value) {
      const option = this.professionTypeOptions.find(item => item.value === value)
      return option ? option.label : value
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
}

.demo-form-inline {
  display: flex;
  align-items: center;
  gap: 10px;
}

.button-area {
  margin-bottom: 15px;
}

.button-area .el-button {
  margin-right: 8px;
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header-wrapper th {
  background-color: #f5f7fa !important;
  font-weight: 600;
}

.pagination-area {
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

.expert-form {
  max-height: 600px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 10px;
}

/* 确保对话框内容不会超出宽度 */
.el-dialog__body {
  overflow-x: hidden;
}

/* 调整表单项宽度，确保在弹窗内正常显示 */
.el-form-item {
  box-sizing: border-box;
}

.el-form-item__content {
  width: 100%;
}

.upload-image {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.avatar-uploader .el-upload {
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.upload-file {
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>